//
//  GroupMemberListViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/7/30.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "GroupMemberListViewController.h"

#import "MemberInformationViewController.h"

#import "FriendModel.h"

#import "FriendListCell.h"

#import "UIImageView+EMWebCache.h"

#import "AddGroupFriendViewController.h"

@interface GroupMemberListViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate,IChatManagerDelegate>
{
    BOOL _isOwner;
}

@property (strong, nonatomic) EMGroup *chatGroup;
@property (nonatomic) GroupType occupantType;

@property (nonatomic, strong) UITableView    * friendTableView;

@property (nonatomic, strong) NSMutableArray * dataSource;
/**装载好友用来搜索*/
@property (nonatomic, strong) NSMutableArray * friendNameArray;

/**搜索结果数组*/
@property (nonatomic, strong) NSMutableArray * resultArray;

@property (nonatomic, strong) UISearchBar    * searchBar;

@property (nonatomic, strong) UISearchDisplayController * searchController;



@end

@implementation GroupMemberListViewController

- (void)registerNotifications {
    [self unregisterNotifications];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)unregisterNotifications {
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)dealloc {
    [self unregisterNotifications];
}


- (instancetype)initWithGroup:(EMGroup *)chatGroup
{
    self = [super init];
    if (self) {
        // Custom initialization
        _chatGroup = chatGroup;
        
        NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
        NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
        _isOwner = [[_chatGroup.owner substringFromIndex:2] isEqualToString:[loginUsername substringFromIndex:2]];

        
        _dataSource = [NSMutableArray array];
        _resultArray = [NSMutableArray array];
        _friendNameArray = [NSMutableArray array];
        _occupantType = GroupMember;
        [self registerNotifications];
    }
    return self;
}

- (instancetype)initWithGroupId:(NSString *)chatGroupId
{
    _dataSource = [NSMutableArray array];
    _resultArray = [NSMutableArray array];
    _friendNameArray = [NSMutableArray array];
    
    EMGroup *chatGroup = nil;
    NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
    for (EMGroup *group in groupArray) {
        if ([group.groupId isEqualToString:chatGroupId]) {
            chatGroup = group;
            NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
            NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
            _isOwner = [group.owner isEqualToString:loginUsername];
            break;
        }
    }
    
    if (chatGroup == nil) {
        chatGroup = [EMGroup groupWithId:chatGroupId];
    }
    
    self = [self initWithGroup:chatGroup];
    if (self) {
        //
    }
    
    return self;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSource = [NSMutableArray array];
        _resultArray = [NSMutableArray array];
        _friendNameArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
//    [detailButton setImage:[UIImage imageNamed:@"group_detail"] forState:UIControlStateNormal];

    if (_isOwner) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addFriends)];
    }
    
    NSLog(@"%@",_chatGroup.groupId) ;

    [self requestForGroupData];
    [self creatUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self requestForGroupData];
}

- (void)requestForGroupData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [SVProgressHUD show];;
    NSDictionary *parameters = @{@"groupid":_groupID};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.hxgroup.user" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"群成员的dictonary :%@",[dictionary description]);
        [_dataSource removeAllObjects];
        [_friendNameArray removeAllObjects];
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                FriendModel * friendModel = [[FriendModel alloc]init];
                [friendModel setValuesForKeysWithDictionary:dataDic];
                
                [_dataSource addObject:friendModel];
                
                [_friendNameArray addObject:friendModel.name];
                
            }
            [_friendTableView reloadData];
            
             _chatDetailViewController.friendNum = [NSString stringWithFormat:@"%ld",(long)[_dataSource count]];
            [SVProgressHUD dismiss];
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}

- (void)creatUI
{
    //搜索框
    //_searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 44)];
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 44)];
    
    _searchBar.placeholder = @"搜索";
    
    //_searchBar.backgroundColor = [UIColor greenColor];
    
    //搜索结果展示
    // 用 searchbar 初始化 SearchDisplayController
    // 并把 searchDisplayController 和当前 controller 关联起来
    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    _searchController.delegate = self;
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchController.searchResultsDelegate = self;
    
    //主界面数据展示
    // _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), SCREEN_W, SCREEN_H-64-44) style:UITableViewStyleGrouped];
    _friendTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    
    
    _friendTableView.backgroundColor = [UIColor whiteColor];
    _friendTableView.dataSource=self;
    _friendTableView.delegate=self;
    
    UINib * nib = [UINib nibWithNibName:@"FriendListCell" bundle:nil];
    
    [_friendTableView registerNib:nib forCellReuseIdentifier:@"ListCell"];
    
    _friendTableView.tableHeaderView = _searchBar;
    _friendTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self.view addSubview:_friendTableView];
    
    
}

#pragma mark - ---------------------------Search Delegate----------------------------

//只要用户在searchbar中输入内容就会触发该方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    //每次搜索之前，清空searchResults
    [_resultArray removeAllObjects];
    NSLog(@"%@", searchString);
    
    //    for (NSArray *section in _dataSourceArry)
    //    {
    //        //通过谓词过滤数据
    //        NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchString];
    //
    //        NSArray *a = [section filteredArrayUsingPredicate:p];
    //
    //        //实现排序
    //        //self == 排序条件
    //        //NO    == 升序(YES)or降序(NO)
    //        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    //        NSArray *s = [a sortedArrayUsingDescriptors:@[sort]];
    //        NSLog(@"%@", s);
    //        [_resultArray addObjectsFromArray:s];
    //    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString];//用于过滤
    _resultArray = [NSMutableArray arrayWithArray:[_friendNameArray filteredArrayUsingPredicate:predicate]];
    
    return YES;
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView != _friendTableView)
    {
        return [_resultArray count];
    }
    else
        return [_friendNameArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell * cell;
    if(tableView != _friendTableView){
        
        static NSString * cellName=@"cell";
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        
//        cell.imageView.image = [UIImage imageNamed:@"chatListCellHead"];
        cell.textLabel.text = [_resultArray objectAtIndex:indexPath.row];
    }else{
        
        FriendListCell *cell;
        cell = (FriendListCell *)[tableView dequeueReusableCellWithIdentifier:@"ListCell"];
        if (cell == nil) {
            cell = [[FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FriendListCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        FriendModel *friendModel = _dataSource[indexPath.row];
        // cell.iconImageView.image = [UIImage imageNamed:@"chatListCellHead.png"];
        
        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:friendModel.img] placeholderImage:[UIImage imageNamed:@"chatListCellHead.png"]];
       // cell.iconImageView.image = [UIImage imageNamed:@"chatListCellHead"];
        cell.friendNameLabel.text = _friendNameArray[indexPath.row];
        //cell.textLabel.text= [_groupNameArray objectAtIndex:indexPath.row];
        
        return cell;
    }
    return cell;
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 22;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //    if (section == 0 || [[self.dataSource objectAtIndex:(section - 1)] count] == 0)
    //    {
    //        return nil;
    //    }
    //
    //    UIView *contentView = [[UIView alloc] init];
    //    [contentView setBackgroundColor:[UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0]];
    //    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 22)];
    //    label.backgroundColor = [UIColor clearColor];
    //    [label setText:[self.sectionTitles objectAtIndex:(section - 1)]];
    //    [contentView addSubview:label];
    //    return contentView;
    
    
    UIView *contentView = [[UIView alloc] init];
    [contentView setBackgroundColor:Lightlightcolor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 22)];
    label.backgroundColor = [UIColor clearColor];
    [label setText:@"群组成员"];
    [contentView addSubview:label];
    return contentView;
}

//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    NSMutableArray * existTitles = [NSMutableArray array];
//    //section数组为空的title过滤掉，不显示
////    for (int i = 0; i < [self.sectionTitles count]; i++) {
////        if ([[self.dataSource objectAtIndex:i] count] > 0) {
////            [existTitles addObject:[self.sectionTitles objectAtIndex:i]];
////        }
////    }
//
//    return existTitles;
//}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
    NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
    
    FriendModel *friendModel = _dataSource[indexPath.row];
    
    if (_isOwner) {
        if(tableView != _friendTableView||[friendModel.hx_username isEqualToString:loginUsername]) {
            return NO;
        }
        return YES;
        
    }else {
        return NO;
    
    }
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView setEditing:YES animated:YES];
    return UITableViewCellEditingStyleDelete;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"删除了第%ld行",(long)indexPath.row);

    FriendModel *friendModel = _dataSource[indexPath.row];

    NSMutableArray *occupants = [NSMutableArray array];
    [occupants addObject:friendModel.hx_username];
    if (_isOwner) {
        [self deleteMemberFromGroup:friendModel];
    }
    
    [tableView setEditing:NO animated:YES];
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView != _friendTableView) {
        for (FriendModel *friendModel in _dataSource)
        {
            if ([_resultArray[indexPath.row] isEqualToString:friendModel.name]) {
                
                MemberInformationViewController *memberInformationViewController = [[MemberInformationViewController alloc] init];
                memberInformationViewController.title = friendModel.name;
                memberInformationViewController.hxUserID = friendModel.hx_username;
                
                [self.navigationController pushViewController:memberInformationViewController animated:NO];
            }
        
        
        }
    
    
    }
    else {
        FriendModel *friendModel = [_dataSource objectAtIndex:indexPath.row];
        
        if (friendModel) {
            MemberInformationViewController *memberInformationViewController = [[MemberInformationViewController alloc] init];
            memberInformationViewController.title = _friendNameArray[indexPath.row];
            FriendModel * friendModel = _dataSource[indexPath.row];
            memberInformationViewController.hxUserID = friendModel.hx_username;
            
            [self.navigationController pushViewController:memberInformationViewController animated:YES];
        }
    }
}

- (void)addFriends {
    AddGroupFriendViewController *addFriendViewController = [[AddGroupFriendViewController alloc]init];
    addFriendViewController.groupID = self.groupID;
    addFriendViewController.groupType = self.groupType;
    
    addFriendViewController.friendArry = [_dataSource copy];
    
    [self.navigationController pushViewController:addFriendViewController animated:YES];

}


- (void)deleteMemberFromGroup:(FriendModel *)friendModel {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *parameters = @{@"groupid":_chatGroup.groupId,
                                 @"username":friendModel.hx_username};
    NSLog(@"%@",parameters);
    [SVProgressHUD show];
    [manager GetWithParameters:parameters method:@"set.hxgroup.user.del" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"删除结果的dictonary :%@",[dictionary description]);
    
        if ([[dictionary objectForKey:@"total"]intValue] == 1)
        {
            [_dataSource removeObject:friendModel];
            [_friendNameArray removeObject:friendModel.name];
            
            NSInteger friendNumber = [_chatDetailViewController.friendNum integerValue];
            friendNumber--;
            
            _chatDetailViewController.friendNum = [NSString stringWithFormat:@"%ld",(long)friendNumber];
            
            [_friendTableView reloadData];
            
            
            
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showErrorWithStatus:error];
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}


@end

